package com.atguigu.gulimall.product.util;

import io.minio.GetObjectArgs;
import io.minio.GetObjectResponse;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

@Component
public class MinioUtil {
    @Resource
    private MinioClient minioClient;
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.bucket}")
    private String bucket;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws Exception
     */
    public String upload(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            PutObjectArgs objectArgs = PutObjectArgs.builder().object(fileName)
                    .bucket(bucket)
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(),file.getSize(),-1).build();

            minioClient.putObject(objectArgs);
            String url = endpoint + "/" + bucket + "/" +  fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    public String uploadBatch(MultipartFile[] files) {
        for(MultipartFile file : files) {
            upload(file);
        }
        return "ok";
    }

    /**
     * 文件下载
     * @param filename
     * @param res
     */
    public void download(String filename, HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucket)
                .object(filename).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len=response.read(buf))!=-1){
                    os.write(buf,0,len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
//                res.setContentType("application/force-download");// 设置强制下载不打开
                res.addHeader("Content-Disposition", "attachment;fileName=" + filename);
                try ( ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
